import React, { useRef, useState, ReactText } from 'react';
import { Spin, Switch, Popconfirm, Button, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { getRoleList, roleDelete } from '@/services/system/role';
import ProTable, { ActionType } from '@ant-design/pro-table';
import Search from 'antd/lib/input/Search';
import RoleAdd from '@/pages/system/role/components/RoleAdd';
import RoleEdit from '@/pages/system/role/components/RoleEdit';
import { DeleteOutlined } from '@ant-design/icons';
import RoleAuth from '@/pages/system/role/components/RoleAuth';
import Tag from 'antd/es/tag';

/**
 * 角色管理
 *
 * @author zhangby
 * @date 23/9/20 2:51 pm
 */
export default (): React.ReactNode => {
  const [loading, setLoading] = useState(false);
  const [rows, setRows] = useState<ReactText[]>([]);
  const [query, setQuery] = useState([]);

  const ref = useRef<ActionType>();

  // 搜索
  const onSearch = (val) => {
    setQuery(val);
    ref.current?.reload();
  };

  // 删除
  const onDelete = async (id: string) => {
    try {
      setLoading(true);
      const data = await roleDelete(id);
      if (data.code === '000') {
        setLoading(false);
        message.success('删除记录成功！');
        // 刷新
        ref.current?.reloadAndRest();
      }
    } catch (e) {
      setLoading(false);
    }
  };

  // 批量删除
  const onBatchDelete = () => {
    if (rows.length === 0) {
      message.error('请选择要操作的记录');
    }
    onDelete(rows.join(','));
  };

  return (
    <>
      <Spin spinning={loading}>
        <PageContainer
          subTitle="系统角色管理"
          extra={[
            <span key="del">
              {rows.length > 0 ? (
                <Popconfirm
                  title="确定要删除选中的记录吗?"
                  onConfirm={onBatchDelete}
                  okText="Yes"
                  cancelText="No"
                >
                  <Button type="primary" danger>
                    <DeleteOutlined />
                    批量删除
                  </Button>
                </Popconfirm>
              ) : null}
            </span>,
            <RoleAdd key="add" refresh={() => ref.current?.reload()} />,
          ]}
        >
          <ProTable<System.SysRole>
            actionRef={ref}
            search={false}
            columns={[
              {
                title: '角色名称',
                dataIndex: 'name',
                width: 150,
                hideInSearch: true,
                render: (_, record) => (
                  <RoleEdit id={record.id} refresh={ref.current?.reload}>
                    <Button style={{ marginLeft: 0, padding: 0 }} type="link">
                      {record.name}
                    </Button>
                  </RoleEdit>
                ),
              },
              {
                title: '英文名称',
                dataIndex: 'enname',
                width: 150,
                hideInSearch: true,
              },
              {
                title: '角色类型',
                dataIndex: 'roleType',
                width: 150,
                hideInSearch: true,
                render: (_, record) => <Tag color="magenta">{record.tails.roleTypeLabel}</Tag>,
              },
              {
                title: '是否可用',
                dataIndex: 'useable',
                width: 150,
                hideInSearch: true,
                render: (item, _) => <Switch size="small" checked={item === '1'} />,
              },
              {
                title: '操作',
                dataIndex: 'option',
                valueType: 'option',
                align: 'center',
                width: 150,
                render: (_, record) => (
                  <>
                    <RoleAuth role={record} />
                    <Popconfirm
                      placement="topRight"
                      title="确定要删除选中的记录吗?"
                      onConfirm={() => onDelete(record.id)}
                      okText="Yes"
                      cancelText="No"
                    >
                      <Button type="primary" shape="circle" danger style={{ marginLeft: 10 }}>
                        <DeleteOutlined />
                      </Button>
                    </Popconfirm>
                  </>
                ),
              },
            ]}
            rowSelection={{
              columnWidth: 20,
              onChange: (selectedRowKeys, _) => setRows(selectedRowKeys),
            }}
            request={(params, sorter, filter) =>
              getRoleList({ ...{ ...params, keyword: query }, sorter, filter })
            }
            pagination={{
              pageSize: 10,
            }}
            rowKey="id"
            headerTitle="角色列表"
            toolBarRender={() => [
              <Search
                placeholder="搜索"
                onSearch={onSearch}
                style={{ minWidth: 400 }}
                enterButton
              />,
            ]}
          />
        </PageContainer>
      </Spin>
    </>
  );
};
